package com.front.controller;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.front.common.DateUtils;
import com.front.common.MD5Util;
import com.front.common.StringUtils;
import com.front.constant.PayConstant;
import com.front.model.UserCharge;
import com.front.service.UserChargeService;

@Controller
public class OnlineChargeController extends BaseController {

	@Autowired
	private UserChargeService userChargeService;
	
	@Value("${platform.pay.externalkey:''}")
	private String externalkey;
	
	@Value("${platform.pay.url:''}")
	private String  payUrl;
	
	@Value("${platform.pay.username:''}")
	private String username;
	
	@Value("${platform.pay.callback:''}")
	private String payBackurl;

	@RequestMapping(value = "/content/charge/chargeSuccess")
	public void chargeSuccess(HttpServletRequest request, HttpServletResponse repson, ModelMap map) throws Exception
	{ 
		String billno=request.getParameter("billno");
		String currency_type=request.getParameter("Currency_type");
		String amount=request.getParameter("amount");
		String mydate=request.getParameter("date");
		String succ=request.getParameter("succ");
		String msg=request.getParameter("msg");
		String attach=request.getParameter("attach");
		String ipsbillno=request.getParameter("ipsbillno");
		String retEncodeType=request.getParameter("retencodetype");
		String signature=request.getParameter("signature");
		//返回订单加密的明文:billno+【订单编号】+currencytype+【币种】+amount+【订单金额】+date+【订单日期】+succ+【成功标志】+ipsbillno+【IPS订单编号】+retencodetype +【交易返回签名方式】+【商户内部证书】 
		StringBuilder content=new StringBuilder();
		content.append("billno").append(billno);
		content.append("currencytype").append(currency_type);
		content.append("amount").append(amount);
		content.append("date").append(mydate);  
		content.append("succ").append(succ);
		content.append("ipsbillno").append(ipsbillno);
		content.append("retencodetype").append(retEncodeType);  //明文：订单编号+订单金额+订单日期+成功标志+IPS订单编号+币种
		content.append(externalkey);
		String cryption =MD5Util.MD5(content.toString());
		if(StringUtils.equalsIgnoreCase(cryption, signature))
		{
			 if(StringUtils.equalsIgnoreCase(succ, "Y"))
			 {
				 UserCharge charge = userChargeService.queryUserCharge(billno);
				 if(charge!=null)//该订单已经删除了 
				 {
					 if(charge.getIsDelete()==PayConstant.CHARGE_NORMAL)
					 {			 
					     if(StringUtils.equals(charge.getStatus(),PayConstant.CHARGE_IS_NOTHANDLE))//未支付的订单
					     { 
					    	 charge.setActualAccount(StringUtils.str2Double(amount));
						     userChargeService.charge(charge);
						     super.renderPage(repson, "交易成功");
						     return;
					     } 
					 } 
				 } 
			 }
			 else
			 {
				 super.renderPage(repson, "验证失败"); 
			 }
		}
		
	
	}

	@RequestMapping(value = "/content/bank/online_recharge/{chargeId}", method = RequestMethod.GET)
	public String contentOnlineRechargeSubmit(HttpServletRequest req, HttpServletResponse resp, ModelMap modelMap, @PathVariable("chargeId") String charge_id) throws Exception
	{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", charge_id);
		modelMap.put("charge",this.reportService.querySingleResult("queryChargeDetail", map));
		modelMap.put("chargeDate", DateUtils.getShortDateString(new Date()));
		modelMap.put("id", charge_id);
		modelMap.put("url", payUrl);
		return "bank/content-recharge-online";
	}

	@RequestMapping(value = "/content/charge/onlineCharge", method = {RequestMethod.POST, RequestMethod.GET })
	public void onlineCharge(HttpServletRequest req,HttpServletResponse response, ModelMap map) throws Exception {
		StringBuilder sb= new StringBuilder();
		String chargeDate = req.getParameter("chargeDate");
		String gatewayType=req.getParameter("gatewayType");
		Map<String,Object>charge =this.reportService.querySingleResult("queryChargeDetail", this.buildQueryMap(req));
		//billno+【订单编号】+ currencytype +【币种】+ amount +【订单金额】+ date +【订单日期】 + orderencodetype +【订单支付接口加密方式】+【商户内部证书字符串】 
		DecimalFormat currentNumberFormat=new DecimalFormat("#0.00");
		String amount =currentNumberFormat.format(StringUtils.str2Double(charge.get("amount")));
		StringBuilder cryption = new StringBuilder();
		cryption.append("billno").append(charge.get("chargeOrder"));
		cryption.append("currencytype").append("RMB");
		cryption.append("amount").append(amount);
		cryption.append("date").append(chargeDate);
		cryption.append("orderencodetype").append(PayConstant.ORDERENCODE_TYPE);
		cryption.append(externalkey);
	    
		sb.append("<body onload=\"document.forms['payform'].submit()\">");
		sb.append("<form id='payform' name='payform' action='").append(payUrl).append("' method='post' >");
		sb.append("<input type='hidden' name='Mer_code' value='").append(username).append("'/>");
		sb.append("<input type='hidden' name='Billno' value='").append(charge.get("chargeOrder")).append("'/>");
		sb.append("<input type='hidden' name='Amount' value='").append(amount);
		sb.append("'/>");
		sb.append("<input type='hidden' name='Date' value='").append(chargeDate).append("'/>");
		sb.append("<input type='hidden' name='Gateway_Type' value='").append(gatewayType).append("'/>");
		sb.append("<input type='hidden' name='Currency_Type' value='RMB'> ");
		sb.append("<input type='hidden' name='RetEncodeType' value='").append(PayConstant.MD5).append("'/>");
		sb.append("<input type='hidden' name='OrderEncodeType' value='").append(PayConstant.ORDERENCODE_TYPE).append("'/>");
		sb.append("<input type='hidden' name='Rettype' value='").append(PayConstant.SERVER_TO_SERVER).append("'>"); 
	    sb.append("<input type='hidden' name='ServerUrl' value='").append(payBackurl).append("'>");
	    sb.append("<input type='hidden' name='Merchanturl' value='").append(payBackurl).append("'>");
	    sb.append("<input type='hidden' name='SignMD5' value='").append(StringUtils.lowerCase(MD5Util.MD5(cryption.toString()))).append("'>");
	    sb.append("</body>");
	    this.renderPage(response, sb.toString());
	}

}
